package com.ant.myagile

import java.text.SimpleDateFormat

import org.hibernate.Criteria;
import org.hibernate.Session
import org.hibernate.SessionFactory
import org.hibernate.criterion.Restrictions
import org.springframework.beans.factory.annotation.Autowired

import com.ant.myagile.utils.CommonUtils




class ProjectService {
	
	@Autowired
	SessionFactory sessionFactory;
	
	static transactional = true
	def springSecurityService
	
	MemberService memberService;
	
	def Project save(Map<String, String> parameters, request, servletContext) {
		Member member = springSecurityService.currentUser
		def theProject = new Project()
		theProject.properties = parameters
		theProject.owner = Member.get(member.id)
		def uploadedFile = request.getFile('imagePath')
		if(!uploadedFile.empty){
			try{
				def webRootDir = servletContext.getRealPath("/")
				def userDir = new File(webRootDir,"/images/imageProject/")
				userDir.mkdirs();
				uploadedFile.transferTo(new File(userDir,uploadedFile.originalFilename))
				theProject.imagePath = uploadedFile.originalFilename
			}
			catch(IOException e){
				e.printStackTrace()
			}
			
		}
		theProject.save()
		for(i in parameters.myCheckbox){
			def teamProject
			SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd");
			String strDate = dateFormat.format(new Date())
			Date dateNow = dateFormat.parse(strDate)
			
			teamProject = new Team_Project(startDate: dateNow, endDate: "")
			def theTeam = Team.get(i)
			def t = 0
			if(theTeam == null){
				theTeam =  Team.get(parameters.myCheckbox)
				t = 1				
			}
			theProject.addToTeamProjects(teamProject)
			theTeam.addToTeamProjects(teamProject)
			//teamProject.save(failOnError : true)
                        if (!teamProject.save()) {
                            teamProject.errors.each {
                                println it
                            }
                        }
			if(t == 1){
				break;
			}
		}
		
		return theProject
	}

	def update(Map<String, String> parameters, request, servletContext){
		Member member = springSecurityService.currentUser
		def theProject = Project.get(parameters.id)
		
		theProject.projectName = parameters.projectName
		theProject.description = parameters.description

		if(parameters.isPublic == null) {
			theProject.isPublic = false;
		}
		else {
			theProject.isPublic = true;
		}
		theProject.owner = Member.get(member.id)
		
		def uploadedFile = request.getFile('imagePath')
		if(!uploadedFile.empty){
			try{
				def webRootDir = servletContext.getRealPath("/")
				def userDir = new File(webRootDir,"/images/imageProject/")
				userDir.mkdirs();
				uploadedFile.transferTo(new File(userDir,uploadedFile.originalFilename))
				theProject.imagePath = uploadedFile.originalFilename
			}
			catch(IOException e){
				e.printStackTrace()
			}
		}
		theProject.save()
		
        
            //Get all teams assigned to project before
            def oldTeam = Team_Project.findAll("from Team_Project as team_project "+
                "where team_project.project = :project", [project: theProject])
            def oldTeamListId = oldTeam.team.id
            def newTeamListId = []
            if (parameters.myCheckbox instanceof String) newTeamListId.add(parameters.myCheckbox)
            else newTeamListId = (parameters.myCheckbox)
            for (oldTeamId in oldTeamListId){
                if (!(oldTeamId in newTeamListId)){
                    def removeTeam = Team_Project.find("from Team_Project as team_project "+
                                        "where team_project.project = :project and team_project.team.id = :team", 
                                        [project: theProject, team: oldTeamId])
                    removeTeam.endDate = CommonUtils.getCurrentDay()
                    removeTeam.save()
                }
            }
            newTeamListId.each() {
                println '111  ' +it
                def editTeam = Team_Project.find("from Team_Project as team_project "+
                    "where team_project.project = :project and team_project.team.id = :team",
                    [project: theProject, team: Long.parseLong(it)])
                //If editTeam exist then change endDate
                if (editTeam != null){
                    editTeam.endDate = null
                    editTeam.save()
                } else {
                //If editTeam not exist then add to database
                    editTeam = new Team_Project()
                    editTeam.project = theProject
                    editTeam.team = Team.get(it)
                    editTeam.startDate = CommonUtils.getCurrentDay()
                    editTeam.save()
                }
            }
		return theProject
	}
	
	
	
	def remove(Map<String, String> parameters) {
		Project.get(parameters.id)?.delete()
	}

	def Project findProject(Map<String, String> parameters) {
		Project.get(parameters.projectIDs)
	}

	def Project[] findAllProjects() {
		Member member = springSecurityService.currentUser
		Project[] pr = Project.findAllByOwner(member)
	}
	
	def Team_Project[] findAllTeams(Map<String, String> parameters){
		Session session = sessionFactory.getCurrentSession();
		List<Team_Project> list = session.createCriteria(Team_Project.class,"teamProjectAlias")
										.createAlias("teamProjectAlias.project", "projectAlias")
										.add(Restrictions.eq("projectAlias.id", Long.parseLong(parameters.projectIDs)))
										.list();
		
		List<Team_Project> list2 = new ArrayList<Team_Project>(0); 
		for(tp in list){
			if(tp.endDate == null){
				list2.add(tp);
			}
		}
		return list2;
	}
	
	def Team[] findTeams(){
		Member member = springSecurityService.currentUser
		if(member){
		Member.get(member.id).team
		}
	}
	
	def Project checkExistProject(String name){
		Session session = sessionFactory.getCurrentSession();
		Member member = springSecurityService.currentUser
		Project project = session.createCriteria(Project.class,"projectAlias")
								 .createAlias("projectAlias.owner", "OwnerAlias")
								 .add(Restrictions.like("projectAlias.projectName", name))	
								 .add(Restrictions.eq("OwnerAlias.id", member.id)).uniqueResult()
		println project
		return project		
	}
	
	def remove(pid)
	{
		try {
			Project project = Project.findById(pid);
			project.delete()
			return true
		} catch(Exception e) {
			return false
		}
	}
	
	def removeTeam(tid,pid){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd");
		String strDate = dateFormat.format(new Date())
		Date dateNow = dateFormat.parse(strDate)
		def cl = Team_Project.count
		Long tidl = Long.parseLong(tid)
		Long pidl = Long.parseLong(pid)
		def teamp = Team_Project.find("from Team_Project as a, Team as b, Project as c where a.team = b and a.project = c and a.team.id = :teamId and a.project.id = :projectId",[teamId: tidl, projectId: pidl])
		Team_Project teamproject = Team_Project.get(teamp.id[0])
		teamproject.endDate = dateNow
		teamproject.save()
		return teamproject ? true: false
	}
	
	
	def findProjectBelongToLoggedInMember()
	{
		Member po = memberService.findLoggedInMember()
		if(po) {
			return po.projects;
		} else {
			return false;
		}
	}
}
